package edu.zut.main.thread;

public class BankTransfer {

    public static void main(String[] args) {

        Account account = new Account(100);
        DrawMoneyThread drawMoneyThread = new DrawMoneyThread(account, 20);
        DrawMoneyThread drawMoneyThread1 = new DrawMoneyThread(account, 75);

        new Thread(drawMoneyThread,"boy").start();
        new Thread(drawMoneyThread1,"girl").start();

    }

}
//转账取款操作
class DrawMoneyThread implements Runnable{
    //账户
    private Account account;
    private int drawMoney; //取款额

    public DrawMoneyThread(Account account,int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }

    //一定要注意，同步代码块或同步方法本质上是一样，都锁定的是某个对象
    //如果run上添加同步关键字，同步的对象即为run所在的线程对象，
    //一定要注意同步的对象时哪一个!!!!!
    @Override
    public void run() {
        //同步代码块实现取款每次只能由一个线程操作
        synchronized (account){
            //取款
            if (account.money < drawMoney){
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money -= drawMoney;
            System.out.println(Thread.currentThread().getName() + "取钱后，余额为：" + account.money);
        }
    }
}

//账户
class Account {

    int money; //账户余额

    public Account(int money) {
        this.money = money;
    }

}

